package works

import (
	"fmt"
	"jihe.common/protos/base_server/proto"
	"jihe.common/tool"
)

func (s *Tx) Create(in *proto.BaseWorksCollectionWorks) (err error) {
	sqlStr := fmt.Sprintf("INSERT INTO %s (id, url, sort, works_collection_id)VALUES($1,$2,$3,$4)", s.Name)
	stmt, err := s.Db.Prepare(sqlStr)
	if err != nil {
		return
	}
	defer stmt.Close()
	for _, v := range in.List {
		v.Id = fmt.Sprintf("%d", tool.GetSnowflakeId())
		_, err = stmt.Exec(v.Id, v.Url, v.Sort, in.Collection.Id)
		if err != nil {
			return
		}
	}
	return
}

func (s *Tx) Delete(worksCollectionId string) (err error) {
	sqlStr := fmt.Sprintf("DELETE FROM %s WHERE works_collection_id = $1", s.Name)
	_, err = s.Db.Exec(sqlStr, worksCollectionId)
	if err != nil {
		return
	}
	return
}

func (s *Model) GetByWorksCollectionId(worksCollectionId string) (ret []*proto.BaseWork, err error) {
	sqlStr := fmt.Sprintf("select id, url, sort, works_collection_id from %s where works_collection_id = $1", s.Name)
	rows, err := s.Db.Query(sqlStr, worksCollectionId)
	if err != nil {
		return
	}
	defer rows.Close()
	for rows.Next() {
		item := &proto.BaseWork{}
		err = rows.Scan(&item.Id, &item.Url, &item.Sort, &item.WorksCollectionId)
		if err != nil {
			return
		}
		ret = append(ret, item)
	}
	return
}
